// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package executor

import (
	"context"
	"fmt"
	"reflect"
	"time"

	"github.com/kumose/kmopt/pkg/checkpoint"
	"github.com/kumose/kmopt/pkg/cluster/ctxt"
	"go.uber.org/zap"
)

var (
	// register checkpoint for ssh command
	sshPoint = checkpoint.Register(
		checkpoint.Field("host", reflect.DeepEqual),
		checkpoint.Field("port", func(a, b any) bool {
			return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
		}),
		checkpoint.Field("user", reflect.DeepEqual),
		checkpoint.Field("sudo", reflect.DeepEqual),
		checkpoint.Field("cmd", reflect.DeepEqual),
	)

	// register checkpoint for scp command
	scpPoint = checkpoint.Register(
		checkpoint.Field("host", reflect.DeepEqual),
		checkpoint.Field("port", func(a, b any) bool {
			return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
		}),
		checkpoint.Field("user", reflect.DeepEqual),
		checkpoint.Field("src", reflect.DeepEqual),
		checkpoint.Field("dst", reflect.DeepEqual),
		checkpoint.Field("download", reflect.DeepEqual),
	)
)

// CheckPointExecutor wraps Executor and inject checkpoints
//
//	ATTENTION please: the result of CheckPointExecutor shouldn't be used to impact
//	                  external system like PD, otherwise, the external system may
//	                  take wrong action.
type CheckPointExecutor struct {
	ctxt.Executor
	config *SSHConfig
}

// Execute implements Executor interface.
func (c *CheckPointExecutor) Execute(ctx context.Context, cmd string, sudo bool, timeout ...time.Duration) (stdout []byte, stderr []byte, err error) {
	point := checkpoint.Acquire(ctx, sshPoint, map[string]any{
		"host": c.config.Host,
		"port": c.config.Port,
		"user": c.config.User,
		"sudo": sudo,
		"cmd":  cmd,
	})
	defer func() {
		point.Release(err,
			zap.String("host", c.config.Host),
			zap.Int("port", c.config.Port),
			zap.String("user", c.config.User),
			zap.Bool("sudo", sudo),
			zap.String("cmd", cmd),
			zap.String("stdout", string(stdout)),
			zap.String("stderr", string(stderr)),
		)
	}()
	if point.Hit() != nil {
		return []byte(point.Hit()["stdout"].(string)), []byte(point.Hit()["stderr"].(string)), nil
	}

	return c.Executor.Execute(ctx, cmd, sudo, timeout...)
}

// Transfer implements Executer interface.
func (c *CheckPointExecutor) Transfer(ctx context.Context, src, dst string, download bool, limit int, compress bool) (err error) {
	point := checkpoint.Acquire(ctx, scpPoint, map[string]any{
		"host":     c.config.Host,
		"port":     c.config.Port,
		"user":     c.config.User,
		"src":      src,
		"dst":      dst,
		"download": download,
		"limit":    limit,
		"compress": compress,
	})
	defer func() {
		point.Release(err,
			zap.String("host", c.config.Host),
			zap.Int("port", c.config.Port),
			zap.String("user", c.config.User),
			zap.String("src", src),
			zap.String("dst", dst),
			zap.Bool("download", download))
	}()
	if point.Hit() != nil {
		return nil
	}

	return c.Executor.Transfer(ctx, src, dst, download, limit, compress)
}
